﻿using Grow.Log.Serilog.Logging;
using Grow.Module.Service;
using Grow.Utils.Exceptions;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Collections.Concurrent;
using SerilogLog = Serilog.Log;

namespace Grow.Log.Serilog.Seq.Logging
{
    public sealed class LoggerProvider : ILoggerProvider, ISupportExternalScope
    {
        private readonly ConcurrentDictionary<string, Logger> _loggers;
        private IExternalScopeProvider? _externalScopeProviderr;
        private readonly LogOptions _logOptions;
        public LoggerProvider(IServiceContext serviceContext)
        {
            _loggers = new();
            _logOptions = serviceContext.GetOptions<LogOptions>();

            if (string.IsNullOrEmpty(_logOptions.SeqServerUrl))
            {
                throw new GrowFrameworkException($"{nameof(_logOptions)}：SeqServerUrl 为空");
            }
            //异步写法
            SerilogLog.Logger = new LoggerConfiguration()
                        .Enrich.FromLogContext()
                        .WriteTo.Console()
                        .WriteTo.Seq(_logOptions.SeqServerUrl)
                        .Enrich.WithProperty("ApplicationName", _logOptions.AppName)
                        .CreateLogger();

        }

        public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName)
        {
            return _loggers.GetOrAdd(categoryName, name =>
               new Logger(name, _externalScopeProviderr ?? NullScopeProvider.Instance, _logOptions));
        }


        public void SetScopeProvider(IExternalScopeProvider scopeProvider)
        {
            _externalScopeProviderr = scopeProvider;

            foreach (Logger logger in _loggers.Values)
            {
                logger.ExternalScopeProvider = _externalScopeProviderr;
            }
        }

        #region Dispose
        private bool disposedValue;

        private void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _loggers.Clear();

                    SerilogLog.CloseAndFlush();
                }

                // TODO: 释放未托管的资源(未托管的对象)并重写终结器
                // TODO: 将大型字段设置为 null
                disposedValue = true;
            }
        }

        // // TODO: 仅当“Dispose(bool disposing)”拥有用于释放未托管资源的代码时才替代终结器
        // ~LoggerProvider()
        // {
        //     // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
        //     Dispose(disposing: false);
        // }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
        #endregion

    }
}